﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using KPIS.GERP.ESS.BLL;
using KPIS.GERP.ESS.MODEL;

using Telerik.Web.UI;
using KPIS.GERP.GFMS.APP.App_UI.Commons;
using KPIS.GERP.GFMS.APP.App_UI.UserControls;
using KPIS.GERP.GFMS.IBLL;
using KPIS.GERP.GFMS.BLL;
using KPIS.GERP.GFMS.MODEL;

namespace KPIS.GERP.GFMS.APP.App_UI.Forms
{
    public partial class ESS_MoneyRequests : System.Web.UI.Page
    {
        Main main = new Main();
        //double sumBath = 0;
        //double sum = 0;
        IBLL_FIM_MoneyRequests mr = new B_FIM_MoneyRequests();
        IBLL_FIM_MoneyRequestDtls mrd = new B_FIM_MoneyRequestDtls();
        IBLL_FIM_MoneyRequestTravelers mrt = new B_FIM_MoneyRequestTravelers();
        IBLL_FIM_MAS_BorrowTypes bt = new B_FIM_MAS_BorrowTypes();
        IBLL_BGM_MAS_Source source = new B_BGM_MAS_Source();
        B_MessageSend send = new B_MessageSend();
        IBLL_FIM_MAS_Contacts con = new B_FIM_MAS_Contacts();
        IBLL_BGM_ProjectOperation pj = new B_BGM_ProjectOperation();
        IBLL_BGM_ProjectOperationExpense pjexp = new B_BGM_ProjectOperationExpense();
        IBLL_BGM_MAS_ExpenseGroup expgrp = new B_BGM_MAS_ExpenseGroup();

        protected void Page_Load(object sender, EventArgs e)
        {
            ////=============== Set Toolbar ================
            //Toolbar1.ParentPanelGrid = PanelGrid;
            //Toolbar1.ParentPanelEdit = PanelEdit;
            //Toolbar1.ParentCmdAddNew = new Toolbar.ParentAddNew(AddNew1);
            //Toolbar1.ParentCmdEdit = new Toolbar.ParentEdit(Edit1);
            //Toolbar1.ParentCmdInsert = new Toolbar.ParentInsert(Insert1);
            //Toolbar1.ParentCmdUpdate = new Toolbar.ParentUpdate(Update1);
            //Toolbar1.ParentCmdDelete = new Toolbar.ParentDelete(Delete1);
            ////============================================

            if (!IsPostBack)
            {
                //================= Test =================
                int year = main.GetSystemControls().default_bgm_year.Value;
                txtBgmYear.Text = year.ToString();
                txtBgmYear.MinValue = year - 10;
                txtBgmYear.MaxValue = year + 1;
                lblWorkAreaSeq.Text = "1";
                //========================================
                lblMode.Text = "AddNew";

                LoadDDLBgmSourceSeq();
                ddlBgmSourceSeq.SelectedIndex = 0;
                LoadRBLBorrowTypeSeqSeq();
                LoadRBLBgmExpGrpSeq();
                DropDownList_Emp1.LoadControl(350, null, null, null, null);
                DropDownList_Emp2.LoadControl(350, null, null, null, null);
                DropDownList_Contact1.LoadControl(null, null);
                DropDownList_BgmProject1.LoadControl(ddlBgmSourceSeq.SelectedValue, txtBgmYear.Text
                    , Session["EmpSeq"].ToString(), 350, null);

                ViewState["MoneyRequestDtlsInfo"] = new List<M_FIM_MoneyRequestDtls>();
                LoadRepeaterTraveler("-1");
                UpdateUI2("AddNew");
                rblTravelerType_SelectedIndexChanged(null, null);
                //Session["M_FIM_MoneyRequestTravelers"] = mrt.GetFull("-1");
                AddNew();
            }

            //DatePicker1.Page_Load(null, null);
        }

        protected void LoadRBLBgmExpGrpSeq()
        {
            rblBgmExpGrpSeq.DataSource = expgrp.GetList(null);
            rblBgmExpGrpSeq.DataBind();

            rblBgmExpGrpSeq.SelectedIndex = 1;
        }

        public void LoadGrdFimMoneyReqDtls()
        {
            string strMoneyReqSeq = (lblMoneyReqSeq.Text.Length > 0 ? lblMoneyReqSeq.Text : null);
            string strBgmSourceSeq = ddlBgmSourceSeq.SelectedValue;
            string strBgmYear = txtBgmYear.Text;
            string strBgmProjOperSeq = DropDownList_BgmProject1.GetSelectedValue();
            string strBgmExpGrpSeq = rblBgmExpGrpSeq.SelectedValue;
            bool bHaveTax = false;

            switch (rblEventSeq.SelectedValue)
            {
                case "12":
                case "17":
                case "18":
                    bHaveTax = true;
                    break;
                case "16":
                    bHaveTax = false;
                    break;
            }

            FIM_MoneyRequestDtls1.LoadRoot(strMoneyReqSeq, strBgmSourceSeq, strBgmYear
                , rblEventSeq.SelectedValue, strBgmProjOperSeq
                , strBgmExpGrpSeq, Session["UserInternalJobsiteSeq"].ToString(), bHaveTax);
        }

        protected void LoadRepeaterTraveler(string strTravelerSeq)
        {
            DataTable dtb = mrt.GetFull(strTravelerSeq);
            RepeaterTraveler.DataSource = dtb;
            RepeaterTraveler.DataBind();

            Session["M_FIM_MoneyRequestTravelers"] = dtb;
        }

        protected void LoadFinishData()
        {
            M_BGM_ProjectOperation ProjectInfo = pj.GetInfo(DropDownList_BgmProject1.GetSelectedValue());
            lblFinEventName.Text = rblBorrowTypeSeq.SelectedItem.Text;
            lblFinMonryReqDate.Text = dpMoneyReqDate.GetStringValue();
            lblFinBgmYear.Text = txtBgmYear.Text;
            lblFinBgmSourceName.Text = ddlBgmSourceSeq.SelectedItem.Text;
            lblFinMoneyReqName.Text = txtMoneyReqName.Text;
            lblFinBgmProjectName.Text = ProjectInfo.bgm_proj_oper_name;
            lblFinApproverName.Text = DropDownList_Emp1.GetComboBox().Text;

            switch (rblEventSeq.SelectedValue)
            {
                case "16" :
                    PanelFinBorrow.Visible = true;
                    PanelFinRequest.Visible = false;
                    lblBorrowTypeName.Text = rblBorrowTypeSeq.SelectedItem.Text;
                    lblBorrowStartDate.Text = dpBorrowStartDate.GetStringValue();
                    lblBorrowEndDate.Text = dpBorrowEndDate.GetStringValue();
                    lblDebtorName.Text = (rblDebtor.SelectedValue == "1" ? Session["UserName"].ToString()
                        : DropDownList_Contact1.GetComboBox().Text);
                    break;
                case "18" :
                    break;
                case "12" :
                    PanelFinBorrow.Visible = false;
                    PanelFinRequest.Visible = true;
                    lblDocRefNo.Text = txtDocRefNo.Text;
                    break;
                case "17" :
                    break;
            }

            LoadFinMoneyReqDtls();
            LoadFinTraveler();
        }

        protected void LoadFinMoneyReqDtls()
        {
            IList<M_FIM_MoneyRequestDtls> listMoneyRequestDtlsInfo = new List<M_FIM_MoneyRequestDtls>();
            RadGrid grdFimMoneyReqDtls = FIM_MoneyRequestDtls1.GetGrid();

            for (int i = 0; i < grdFimMoneyReqDtls.Items.Count; i++)
            {
                Nullable<double> dAmount = ((RadNumericTextBox)grdFimMoneyReqDtls.Items[i]["amount"].FindControl("txtAmount")).Value;

                if (dAmount > 0)
                {
                    M_FIM_MoneyRequestDtls MoneyRequestDtlsInfo = new M_FIM_MoneyRequestDtls();
                    M_BGM_ProjectOperationExpense SubInfo1 = new M_BGM_ProjectOperationExpense();
                    M_BGM_ProjectExpense SubInfo2 = new M_BGM_ProjectExpense();
                    M_BGM_MAS_Expense SubInfo3 = new M_BGM_MAS_Expense();

                    SubInfo3.bgm_exp_name = grdFimMoneyReqDtls.Items[i]["m_bgm_projectoperationexpense.m_bgm_projectexpense.m_bgm_mas_expense.bgm_exp_name"].Text;
                    SubInfo2.m_bgm_mas_expense = SubInfo3;
                    SubInfo1.m_bgm_projectexpense = SubInfo2;
                    MoneyRequestDtlsInfo.m_bgm_projectoperationexpense = SubInfo1;
                    MoneyRequestDtlsInfo.amount = dAmount;

                    listMoneyRequestDtlsInfo.Add(MoneyRequestDtlsInfo);
                }
            }

            RepeaterDtls.DataSource = listMoneyRequestDtlsInfo;
            RepeaterDtls.DataBind();
        }

        protected void LoadFinTraveler()
        {
            RepeaterFinTraveler.DataSource = (DataTable)Session["M_FIM_MoneyRequestTravelers"];
            RepeaterFinTraveler.DataBind();
        }

        protected void AddNew()
        {
            lblMode.Text = "AddNew";
            lblMoneyReqSeq.Text = "";
            dpMoneyReqDate.SetValue(DateTime.Today.ToShortDateString());
            main.UpdateTabStrip(RadTabStrip1, 0, lblMode.Text);
            UpdateTabPanel(0);
            cmdAddNew.Visible = false;
        }

        protected void Edit(string strSeq)
        {
            Session["ReportSeq"] = strSeq;
            bool bHaveTax = false;
            lblMode.Text = "Edit";
            M_FIM_MoneyRequests info = mr.GetInfo(strSeq);

            rblEventSeq.SelectedValue = info.event_seq.ToString();
            ddlBgmSourceSeq.SelectedValue = info.bgm_source_seq.ToString();
            LoadRBLBorrowTypeSeqSeq();
            txtBgmYear.Text = info.bgm_year.ToString();
            rblBgmExpGrpSeq.SelectedValue = info.bgm_exp_grp_seq.ToString();

            dpMoneyReqDate.SetValue(info.money_req_date);//((info.money_req_date == null ? null : info.money_req_date.Value));
            txtMoneyReqName.Text = info.money_req_name;
            DropDownList_BgmProject1.SetSelectedValue(info.bgm_proj_oper_seq.ToString());
            DropDownList_Emp1.SetSelectedValue(info.approver_seq.ToString());

            switch (info.event_seq.ToString())
            {
                case "12" :
                    txtDocRefNo.Text = info.doc_ref_no;
                    bHaveTax = true;
                    cmdReportMoneyReqContracts.Visible = false;
                    break;
                case "16" :
                    rblBorrowTypeSeq.SelectedValue = info.borrow_type_seq.ToString();
                    bHaveTax = false;
                    //string strBorrowStartDate = "";
                    //string strBorrowEndDate = "";

                    //if (info.borrow_start_date != null || info.borrow_start_date.ToString().Length > 0)
                    //    strBorrowStartDate = info.borrow_start_date.Value.ToShortDateString();
                    //if (info.borrow_end_date != null || info.borrow_end_date.ToString().Length > 0)
                    //    strBorrowEndDate = info.borrow_end_date.Value.ToShortDateString();

                    dpBorrowStartDate.SetValue((info.borrow_start_date == null ? "" : info.borrow_start_date.Value.ToShortDateString()));
                    dpBorrowEndDate.SetValue((info.borrow_end_date == null ? "" : info.borrow_end_date.Value.ToShortDateString()));
                    lblBorrowReturnDate.Text = (info.borrow_return_date == null ? "" : info.borrow_return_date.Value.ToShortDateString());
                    rblDebtor.SelectedValue = (info.debtor_emp_seq.ToString().Length > 0 
                        ? "1" : "2");

                    PanelDetorContactPerson.Visible = rblDebtor.SelectedValue == "2";
                    if (rblDebtor.SelectedValue == "2")
                    {
                        DropDownList_Contact1.SetSelectedValue(info.debtor_contact_seq.ToString());
                    }

                    LoadRepeaterTraveler(strSeq);
                    cmdReportMoneyReqContracts.Visible = true;
                    break;
                case "17" :
                    bHaveTax = true;
                    cmdReportMoneyReqContracts.Visible = false;
                    break;
                case "18" :
                    bHaveTax = true;
                    cmdReportMoneyReqContracts.Visible = false;
                    break;
            }

            FIM_MoneyRequestDtls1.LoadRoot(strSeq, info.bgm_source_seq.ToString(), info.bgm_year.ToString()
                , info.event_seq.ToString(), info.bgm_proj_oper_seq.ToString(), info.bgm_exp_grp_seq.ToString()
                , Session["UserInternalJobsiteSeq"].ToString(), bHaveTax);
            LoadFinishData();
            RadTabStrip1.SelectedIndex = 3;
            RadTabStrip1_TabClick(null, null);
            cmdAddNew.Visible = true;
        }

        private bool CheckData1()
        {
            bool bOK = true;
            string strError = "";
            string strBgmSourceSeq = ddlBgmSourceSeq.SelectedValue;
            string strMoneyReqDate = dpMoneyReqDate.GetStringValue();
            string strApproverSeq = DropDownList_Emp1.GetSelectedValue();

            if (strBgmSourceSeq.Length == 0)
            {
                bOK = false;
                strError = "กรุณากรอกข้อมูล [แหล่งเงิน] !!";
                imgBgmSourceSeq.Visible = true;
            }
            else if (strMoneyReqDate.Length == 0)
            {
                bOK = false;
                strError = "กรุณากรอกข้อมูล [วันที่ทำรายการ] !!";
                imgMoneyReqDate.Visible = true;
            }
            else if (strApproverSeq.Length == 0)
            {
                bOK = false;
                strError = "กรุณากรอกข้อมูล [เสนอผู้บังคับบัญชา] !!";
                imgApprover.Visible = true;
            }
            else
            {
                imgBgmSourceSeq.Visible = false;
                imgMoneyReqDate.Visible = false;
                imgApprover.Visible = false;
            }

            lblError.Text = strError;
            return bOK;
        }

        private bool CheckData2()
        {
            bool bOK = true;
            string strError = "";
            string strContactSeq = DropDownList_Contact1.GetSelectedValue();

            if (strContactSeq.Length == 0 && rblDebtor.SelectedValue == "2")
            {
                bOK = false;
                strError = "กรุณากรอกข้อมูล [ชื่อบุคคลภายนอก] !!";
                //imgContact1.Visible = true;
            }
            else
            {
                //imgContact1.Visible = false;
            }

            lblError.Text = strError;
            return bOK;
        }

        private bool CheckData3()
        {
            bool bOK = true;
            string strError = "";
            string strDocRefNo = txtDocRefNo.Text;

            if (strDocRefNo.Length == 0)
            {
                bOK = false;
                strError = "กรุณากรอกข้อมูล [เลขที่ใบสำคัญที่ใช้ขอเบิก] !!";
                imgDocRefNo.Visible = true;
            }
            else
            {
                imgDocRefNo.Visible = false;
            }

            lblError.Text = strError;
            return bOK;
        }

        protected void LoadDDLBgmSourceSeq()
        {
            ddlBgmSourceSeq.DataSource = source.GetFull(true);
            ddlBgmSourceSeq.DataBind();
        }

        protected void LoadRBLBorrowTypeSeqSeq()
        {
            rblBorrowTypeSeq.DataSource = bt.GetList(ddlBgmSourceSeq.SelectedValue);
            rblBorrowTypeSeq.DataBind();

            if (rblBorrowTypeSeq.Items.Count > 0)
                rblBorrowTypeSeq.SelectedIndex = 0;
        }

        protected void RadTabStrip1_TabClick(object sender, RadTabStripEventArgs e)
        {
            int i = RadTabStrip1.SelectedIndex;

            UpdateTabPanel(i);
            main.UpdateTabStrip(RadTabStrip1, i, lblMode.Text);
        }

        private void UpdateTabPanel(int i)
        {
            switch (i)
            {
                case 0:
                    PanelHead.Visible = true;
                    PanelBorrow.Visible = false;
                    PanelBorrowCreditCard.Visible = false;
                    PanelRequest.Visible = false;
                    PanelRequestNoPlan.Visible = false;
                    PanelDtls.Visible = false;
                    PanelFinish.Visible = false;

                    cmdPrev.Visible = false;
                    cmdNext.Visible = true;
                    cmdInsert.Visible = false;
                    cmdUpdate.Visible = false;
                    break;
                case 1:
                    PanelHead.Visible = false;
                    PanelBorrow.Visible = (rblEventSeq.SelectedValue == "16");
                    PanelBorrowCreditCard.Visible = (rblEventSeq.SelectedValue == "18");
                    PanelRequest.Visible = (rblEventSeq.SelectedValue == "12");
                    PanelRequestNoPlan.Visible = (rblEventSeq.SelectedValue == "17");
                    PanelDtls.Visible = false;
                    PanelFinish.Visible = false;

                    cmdPrev.Visible = true;
                    cmdNext.Visible = true;
                    cmdInsert.Visible = false;
                    cmdUpdate.Visible = false;
                    rblBorrowTypeSeq_SelectedIndexChanged(null, null);
                    break;
                case 2:
                    PanelHead.Visible = false;
                    PanelBorrow.Visible = false;
                    PanelBorrowCreditCard.Visible = false;
                    PanelRequest.Visible = false;
                    PanelRequestNoPlan.Visible = false;
                    PanelDtls.Visible = true;
                    PanelFinish.Visible = false;

                    cmdPrev.Visible = true;
                    cmdNext.Visible = true;
                    cmdInsert.Visible = false;
                    cmdUpdate.Visible = false;
                    break;
                case 3:
                    PanelHead.Visible = false;
                    PanelBorrow.Visible = false;
                    PanelBorrowCreditCard.Visible = false;
                    PanelRequest.Visible = false;
                    PanelRequestNoPlan.Visible = false;
                    PanelDtls.Visible = false;
                    PanelFinish.Visible = true;

                    cmdPrev.Visible = true;
                    cmdNext.Visible = false;
                    cmdInsert.Visible = (lblMode.Text == "AddNew");
                    cmdUpdate.Visible = (lblMode.Text == "Edit");
                    break;
            }
        }

        protected void ddlBgmSourceSeq_SelectedIndexChanged(object o, RadComboBoxSelectedIndexChangedEventArgs e)
        {
            LoadRBLBorrowTypeSeqSeq();
            DropDownList_BgmProject1.LoadControl(ddlBgmSourceSeq.SelectedValue, null
                , Session["EmpSeq"].ToString(), null, null);
        }

        protected void rblDetor_SelectedIndexChanged(object sender, EventArgs e)
        {
            PanelDetorContactPerson.Visible = rblDebtor.SelectedValue == "2";
        }

        protected void cmdNext_Click(object sender, EventArgs e)
        {
            int i = RadTabStrip1.SelectedIndex;

            switch (i)
            {
                case 0 :
                    if (!CheckData1())
                        return;
                    break;
                case 1 :
                    if (!CheckData2())
                        return;
                    break;
                case 2 :
                    LoadFinishData();
                    break;
            }

            RadTabStrip1.SelectedIndex = i + 1;
            main.UpdateTabStrip(RadTabStrip1, i + 1, lblMode.Text);
            UpdateTabPanel(i + 1);
        }

        protected void cmdPrev_Click(object sender, EventArgs e)
        {
            int i = RadTabStrip1.SelectedIndex;

            RadTabStrip1.SelectedIndex = i - 1;
            main.UpdateTabStrip(RadTabStrip1, i - 1, lblMode.Text);
            UpdateTabPanel(i - 1);
        }

        protected void cmdInsert_Click(object sender, EventArgs e)
        {
            string strMoneyReqSeq = null;
            string strBgmSourceSeq = ddlBgmSourceSeq.SelectedValue;
            string strBgmYear = txtBgmYear.Text;
            string strBgmExpGrpSeq = rblBgmExpGrpSeq.SelectedValue;
            string strWorkAreaSeq = lblWorkAreaSeq.Text;
            string strMoneyReqDate = dpMoneyReqDate.GetStringValue();
            string strMoneyReqName = txtMoneyReqName.Text;
            string strEventSeq = rblEventSeq.SelectedValue;
            string strProjectSeq = DropDownList_BgmProject1.GetSelectedValue();
            string strApproverSeq = DropDownList_Emp1.GetSelectedValue();
            string strDocRefNo = null;
            string strBorrowTypeSeq = null;
            string strBorrowStartDate = null;
            string strBorrowEndDate = null;
            string strBorrowReturnDate = null;
            string strDebtorContactSeq = null;
            string strUserID = Session["EmpSeq"].ToString();
            string strSendText = null;
            DateTime dtNow = DateTime.Now;
            M_FIM_MoneyRequests Info = new M_FIM_MoneyRequests();

            switch (strEventSeq)
            {
                case "16" :
                    strBorrowTypeSeq = rblBorrowTypeSeq.SelectedValue;
                    strBorrowStartDate = dpBorrowStartDate.GetStringValue();
                    strBorrowEndDate = dpBorrowEndDate.GetStringValue();
                    strBorrowReturnDate = lblBorrowReturnDate.Text;

                    if (rblDebtor.SelectedValue != "1")
                    {
                        strDebtorContactSeq = DropDownList_Contact1.GetSelectedValue();
                    }

                    strSendText = "คำร้องขอยืมเงิน [" + strMoneyReqName + "] เพื่อพิจารณา";
                    break;
                case "12" :
                    strDocRefNo = txtDocRefNo.Text;

                    strSendText = "คำร้องขอเบิกเงิน [" + strMoneyReqName + "] เพื่อพิจารณา";
                    break;
                case "17" :
                    break;
            }

            Info.bgm_source_seq = main.ConvertNullInt(strBgmSourceSeq);
            Info.bgm_year = main.ConvertNullInt(strBgmYear);
            Info.bgm_exp_grp_seq = main.ConvertNullInt(strBgmExpGrpSeq);
            Info.work_area_seq = main.ConvertNullInt(strWorkAreaSeq);
            Info.event_seq = main.ConvertNullInt(strEventSeq);
            Info.use_advance = "0";
            Info.bgm_proj_oper_seq = main.ConvertNullInt(strProjectSeq);
            Info.money_req_date = main.ConvertNullDateTime(strMoneyReqDate);
            Info.money_req_name = strMoneyReqName;
            Info.ref_no = null;
            Info.doc_ref_no = strDocRefNo;
            Info.borrow_no = null;
            Info.borrow_type_seq = main.ConvertNullInt(strBorrowTypeSeq);
            Info.borrow_start_date = main.ConvertNullDateTime(strBorrowStartDate);
            Info.borrow_end_date = main.ConvertNullDateTime(strBorrowEndDate);
            Info.borrow_return_date = main.ConvertNullDateTime(strBorrowReturnDate);
            Info.approver_seq = main.ConvertNullInt(strApproverSeq);
            Info.emp_seq = main.ConvertNullInt(strUserID);
            Info.debtor_emp_seq = main.ConvertNullInt(strUserID);
            Info.debtor_contact_seq = main.ConvertNullInt(strDebtorContactSeq);
            Info.created_by = main.ConvertNullInt(strUserID);
            Info.created_when = main.ConvertNullDateTime(dtNow);

            strMoneyReqSeq = mr.Insert(Info);
            FIM_MoneyRequestDtls1.Insert(strMoneyReqSeq);

            if (PanelFinTraveler.Visible)
            {
                DataTable dtb = (DataTable)Session["M_FIM_MoneyRequestTravelers"];
                for (int i = 0; i < dtb.Rows.Count; i++)
                {
                    DataRow dr = dtb.Rows[i];
                    string strEmpSeq = dr["emp_seq"].ToString();
                    string strContactSeq = dr["contact_seq"].ToString();
                    //string strContactPersonSeq = dr["contact_person_seq"].ToString();
                    string strJobsiteSeq = dr["job_site_seq"].ToString();
                    string strPosSeq = dr["pos_seq"].ToString();
                    string strClassSeq = dr["class_seq"].ToString();
                    string strOldClassSeq = dr["old_class_seq"].ToString();
                    string strRecordStatus = "U";

                    mrt.Insert(strMoneyReqSeq, strEmpSeq, strContactSeq, "", strJobsiteSeq
                        , strPosSeq, strClassSeq, strOldClassSeq, strRecordStatus, strUserID);
                }
            }
             
            M_MessageSend sendInfo = new M_MessageSend();
            sendInfo.send_date = Info.money_req_date;
            sendInfo.send_text = strSendText;
            sendInfo.ref_no = null;
            sendInfo.ref_seq = main.ConvertNullInt(strMoneyReqSeq);
            sendInfo.ref_type = "fim_money_requests";
            sendInfo.from_emp_seq = main.ConvertNullInt(strUserID);
            sendInfo.from_pos_seq = send.GetPosSeqFromEmpSeq(strUserID);
            sendInfo.wod_emp_seq = null;
            sendInfo.to_emp_seq = main.ConvertNullInt(strApproverSeq); 
            sendInfo.to_pos_seq = send.GetPosSeqFromEmpSeq(strApproverSeq); 
            sendInfo.message_status = "0";
            sendInfo.created_by = main.ConvertNullInt(strUserID);
            sendInfo.created_when = main.ConvertNullDateTime(dtNow);

            send.Insert(sendInfo);

            AddNew();
        }

        protected void cmdUpdate_Click(object sender, EventArgs e)
        {
            string strMoneyReqSeq = lblMoneyReqSeq.Text;
            string strBgmSourceSeq = ddlBgmSourceSeq.SelectedValue;
            string strBgmYear = txtBgmYear.Text;
            string strBgmExpGrpSeq = rblBgmExpGrpSeq.SelectedValue;
            string strWorkAreaSeq = lblWorkAreaSeq.Text;
            string strMoneyReqDate = dpMoneyReqDate.GetStringValue();
            string strMoneyReqName = txtMoneyReqName.Text;
            string strEventSeq = rblEventSeq.SelectedValue;
            string strProjectSeq = DropDownList_BgmProject1.GetSelectedValue();
            string strApproverSeq = DropDownList_Emp1.GetSelectedValue();
            string strDocRefNo = null;
            string strBorrowTypeSeq = null;
            string strBorrowStartDate = null;
            string strBorrowEndDate = null;
            string strBorrowReturnDate = null;
            string strDebtorContactSeq = null;
            string strUserID = Session["EmpSeq"].ToString();
            string strSendText = null;
            DateTime dtNow = DateTime.Now;
            M_FIM_MoneyRequests Info = new M_FIM_MoneyRequests();

            switch (strEventSeq)
            {
                case "16":
                    strBorrowTypeSeq = rblBorrowTypeSeq.SelectedValue;
                    strBorrowStartDate = dpBorrowStartDate.GetStringValue();
                    strBorrowEndDate = dpBorrowEndDate.GetStringValue();
                    strBorrowReturnDate = lblBorrowReturnDate.Text;

                    if (rblDebtor.SelectedValue != "1")
                    {
                        strDebtorContactSeq = DropDownList_Contact1.GetSelectedValue();
                    }

                    strSendText = "คำร้องขอยืมเงิน [" + strMoneyReqName + "] เพื่อพิจารณา";
                    break;
                case "12":
                    strDocRefNo = txtDocRefNo.Text;
                    strSendText = "คำร้องขอเบิกเงิน [" + strMoneyReqName + "] เพื่อพิจารณา";
                    break;
                case "17":
                    break;
            }

            Info.money_req_seq = Convert.ToInt32(strMoneyReqSeq);
            Info.bgm_source_seq = main.ConvertNullInt(strBgmSourceSeq);
            Info.bgm_year = main.ConvertNullInt(strBgmYear);
            Info.bgm_exp_grp_seq = main.ConvertNullInt(strBgmExpGrpSeq);
            Info.work_area_seq = main.ConvertNullInt(strWorkAreaSeq);
            Info.event_seq = main.ConvertNullInt(strEventSeq);
            Info.use_advance = "0";
            Info.bgm_proj_oper_seq = main.ConvertNullInt(strProjectSeq);
            Info.money_req_date = main.ConvertNullDateTime(strMoneyReqDate);
            Info.money_req_name = strMoneyReqName;
            Info.ref_no = null;
            Info.doc_ref_no = strDocRefNo;
            Info.borrow_no = null;
            Info.borrow_type_seq = main.ConvertNullInt(strBorrowTypeSeq);
            Info.borrow_start_date = main.ConvertNullDateTime(strBorrowStartDate);
            Info.borrow_end_date = main.ConvertNullDateTime(strBorrowEndDate);
            Info.borrow_return_date = main.ConvertNullDateTime(strBorrowReturnDate);
            Info.approver_seq = main.ConvertNullInt(strApproverSeq);
            Info.emp_seq = main.ConvertNullInt(strUserID);
            Info.debtor_emp_seq = main.ConvertNullInt(strUserID);
            Info.debtor_contact_seq = main.ConvertNullInt(strDebtorContactSeq);
            Info.updated_by = main.ConvertNullInt(strUserID);
            Info.updated_when = main.ConvertNullDateTime(dtNow);

            mr.Update(Info);
            FIM_MoneyRequestDtls1.Update(strMoneyReqSeq);

            if (PanelFinTraveler.Visible)
            {
                DataTable dtb = (DataTable)Session["M_FIM_MoneyRequestTravelers"];
                for (int i = 0; i < dtb.Rows.Count; i++)
                {
                    DataRow dr = dtb.Rows[i];
                    string strTravelerSeq = dr["traveler_seq"].ToString();
                    string strEmpSeq = dr["emp_seq"].ToString();
                    string strContactSeq = dr["contact_seq"].ToString();
                    string strContactPersonSeq = dr["contact_person_seq"].ToString();
                    string strJobsiteSeq = dr["job_site_seq"].ToString();
                    string strPosSeq = dr["pos_seq"].ToString();
                    string strClassSeq = dr["class_seq"].ToString();
                    string strOldClassSeq = dr["old_class_seq"].ToString();
                    string strRecordStatus = "U";

                    if (strTravelerSeq == null || strTravelerSeq.Length == 0)
                    {
                        mrt.Insert(strMoneyReqSeq, strEmpSeq, strContactSeq, strContactPersonSeq, strJobsiteSeq
                            , strPosSeq, strClassSeq, strOldClassSeq, strRecordStatus, strUserID);
                    }
                    else
                    {
                        mrt.Update(strTravelerSeq, strMoneyReqSeq, strEmpSeq, strContactSeq, strContactPersonSeq
                            , strJobsiteSeq, strPosSeq, strClassSeq, strOldClassSeq, strUserID);
                    }
                }

                DataTable dtbDeleted = (DataTable)Session["M_FIM_MoneyRequestTravelers_Deleted"];
                for (int i = 0; i < dtbDeleted.Rows.Count; i++)
                {
                    DataRow drDeleted = dtbDeleted.Rows[i];
                    string strTravelerSeq = drDeleted["traveler_seq"].ToString();

                    if (strTravelerSeq != null && strTravelerSeq.Length > 0)
                    {
                        mrt.Delete(strTravelerSeq, strUserID);
                    }
                }
            }

            M_MessageSend sendInfo = send.GetInfoFromRefSeq(strMoneyReqSeq, "fim_money_requests");
            sendInfo.send_date = Info.money_req_date;
            sendInfo.send_text = strSendText;
            sendInfo.ref_seq = main.ConvertNullInt(strMoneyReqSeq);
            sendInfo.from_emp_seq = main.ConvertNullInt(strUserID);
            sendInfo.from_pos_seq = send.GetPosSeqFromEmpSeq(strUserID);
            sendInfo.to_emp_seq = main.ConvertNullInt(strApproverSeq);
            sendInfo.to_pos_seq = send.GetPosSeqFromEmpSeq(strApproverSeq);
            sendInfo.updated_by = main.ConvertNullInt(strUserID);
            sendInfo.updated_when = main.ConvertNullDateTime(dtNow);

            send.Update(sendInfo);

            AddNew();
        }

        protected void RadAjaxManager1_AjaxRequest(object sender, AjaxRequestEventArgs e)
        {
            lblMoneyReqSeq.Text = e.Argument;
            Edit(e.Argument);
        }

        protected void rblBorrowTypeSeq_SelectedIndexChanged(object sender, EventArgs e)
        {
            M_FIM_MAS_BorrowTypes info = bt.GetInfo(rblBorrowTypeSeq.SelectedValue);

            if (info.cal_date_type == "2")
            {
                cmdCalReturnDate.Visible = true;
                cmdCalReturnDate_Click(null, null);
                lblBorrowReturnDate.Visible = true;
                PanelTraveler.Visible = true;
                PanelFinTraveler.Visible = true;
            }
            else
            {
                cmdCalReturnDate.Visible = false;
                lblBorrowReturnDate.Visible = false;
                PanelTraveler.Visible = false;
                PanelFinTraveler.Visible = false;
            }
        }

        protected void cmdCalReturnDate_Click(object sender, EventArgs e)
        {
            if (dpBorrowEndDate.GetDateValue() != null)
            {
                string strBorrowTypeSeq = rblBorrowTypeSeq.SelectedValue;
                DateTime dtBorrowStartDate = dpBorrowStartDate.GetDateValue().Value;
                DateTime dtBorrowEndDate = dpBorrowEndDate.GetDateValue().Value;
                DateTime dtBorrowReturnDate;

                M_FIM_MAS_BorrowTypes info = bt.GetInfo(rblBorrowTypeSeq.SelectedValue);
                dtBorrowReturnDate = dtBorrowEndDate.AddDays(info.return_day.Value);
                lblBorrowReturnDate.Text = dtBorrowReturnDate.ToShortDateString();
                string strDayCount = (dtBorrowEndDate - dtBorrowStartDate).ToString();
                strDayCount = strDayCount.Substring(0, strDayCount.IndexOf("."));
                Session["strDayCount"] = strDayCount;
            }
        }

        protected void rblBgmExpGrpSeq_SelectedIndexChanged(object sender, EventArgs e)
        {
            LoadGrdFimMoneyReqDtls();
        }

        protected void RepeaterTraveler_ItemCommand(object source, RepeaterCommandEventArgs e)
        {
            string strCommandName = e.CommandName;

            if (strCommandName.Length > 0)
            {
                DataTable dtb = ((DataTable)Session["M_FIM_MoneyRequestTravelers"]);

                if (strCommandName == "delete")
                {
                    if (cmdUpdate1.Visible == true)
                    {
                        return;
                    }
                    DataTable dtbDeleted = ((DataTable)Session["M_FIM_MoneyRequestTravelers_Deleted"]);
                    dtb.Rows.RemoveAt(e.Item.ItemIndex);
                    dtbDeleted.Rows.Add(dtb.Rows[e.Item.ItemIndex]);

                    RepeaterTraveler.DataSource = dtb;
                    RepeaterTraveler.DataBind();

                    Session["M_FIM_MoneyRequestTravelers"] = dtb;
                    Session["M_FIM_MoneyRequestTravelers_Deleted"] = dtbDeleted;
                }
                else if (strCommandName == "edit")
                {
                    DataRow dr = dtb.Rows[e.Item.ItemIndex];

                    lblTravelerSeq.Text = main.WebString(dr["traveler_seq"].ToString());
                    //lblMoneyReqSeq.Text = main.WebString(dr["money_req_seq"].ToString());
                    string strEmpSeq = main.WebString(dr["emp_seq"].ToString());

                    if (strEmpSeq.Length > 0)
                    {
                        DropDownList_Emp2.SetSelectedValue(strEmpSeq);
                        DropDownList_Emp2.SelectedIndexChanged(strEmpSeq);
                    }
                    else
                    {
                        DropDownList_Contact2.SetSelectedValue(dr["contact_seq"].ToString());
                        //DropDownList_ContactPerson2.SetSelectedValue(dr["contact_person_seq"].ToString());
                    }

                    ViewState["Index"] = e.Item.ItemIndex;
                    UpdateUI2("Edit");

                    cmdUpdate1.Focus();
                }
            }
        }

        protected void UpdateUI2(string strMode)
        {
            switch (strMode)
            {
                case "AddNew" :
                    lblCommand.Text = "เพิ่มรายการใหม่";
                    cmdInsert1.Visible = true;
                    cmdUpdate1.Visible = false;
                    break;
                case "Edit" :
                    lblCommand.Text = "แก้ไขรายการ";
                    cmdInsert1.Visible = false;
                    cmdUpdate1.Visible = true;
                    break;
            }
        }

        protected void rblTravelerType_SelectedIndexChanged(object sender, EventArgs e)
        {
            bool bEmp = rblTravelerType.SelectedValue == "1";

            PanelEmp.Visible = bEmp;
            PanelContact.Visible = !bEmp;
        }

        protected void cmdInsert1_Click(object sender, EventArgs e)
        {
            string strTravelSeq = lblTravelerSeq.Text;
            string strMoneyReqSeq = lblMoneyReqSeq.Text;
            string strEmpSeq = null;
            string strContactSeq = null;
            string strContactPersonSeq = null;
            DataTable dtb = (DataTable)Session["M_FIM_MoneyRequestTravelers"];
            DataRow dr = dtb.NewRow();

            //dr["traveler_seq"] = strTravelSeq;
            //dr["money_req_seq"] = strMoneyReqSeq;
            //dr["traveler_seq"] = (strTravelSeq.Length > 0 ? strTravelSeq : DBNull.Value);
            dr["money_req_seq"] = main.ConvertToDB(strMoneyReqSeq);//(strMoneyReqSeq.Length > 0 ? strMoneyReqSeq : null);

            if (rblTravelerType.SelectedValue == "1")
            {
                strEmpSeq = DropDownList_Emp2.GetSelectedValue();

                dr["emp_seq"] = main.ConvertToDB(strEmpSeq);
                dr["job_site_seq"] = main.ConvertToDB(lblJobSiteSeq.Text);
                dr["pos_seq"] = main.ConvertToDB(lblPosSeq.Text);
                dr["class_seq"] = main.ConvertToDB(lblClassSeq.Text);
                dr["old_class_seq"] = main.ConvertToDB(lblOldClassSeq.Text);

                dr["traveler_name"] = main.ConvertToDB(DropDownList_Emp2.GetComboBox().Text);
                dr["job_site_name"] = main.ConvertToDB(lblJobSiteName.Text);
                dr["pos_name"] = main.ConvertToDB(lblPosName.Text);
                dr["class_name"] = main.ConvertToDB(lblClassName.Text);
                dr["old_class_name"] = main.ConvertToDB(lblOldClassName.Text);
            }
            else
            {
                strContactSeq = DropDownList_Contact2.GetSelectedValue();
                //strContactPersonSeq = DropDownList_ContactPerson2.GetSelectedValue();

                dr["contact_seq"] = main.ConvertNullInt(strContactSeq);
                dr["contact_person_seq"] = main.ConvertNullInt(strContactPersonSeq);

                if (DropDownList_Contact2.GetSelectedValue().Length > 0)
                {
                    dr["traveler_name"] = DropDownList_Contact2.GetComboBox().Text;
                }
                else
                {
                    dr["traveler_name"] = "";
                }
            }

            //DataTable dtb = (DataTable)Session["M_FIM_MoneyRequestTravelers"];
            dtb.Rows.Add(dr);

            RepeaterTraveler.DataSource = dtb;
            RepeaterTraveler.DataBind();

            Session["M_FIM_MoneyRequestTravelers"] = dtb;
            ResetControl();
        }

        protected void cmdUpdate1_Click(object sender, EventArgs e)
        {
            string strTravelSeq = lblTravelerSeq.Text;
            string strMoneyReqSeq = lblMoneyReqSeq.Text;
            string strEmpSeq = null;
            string strContactSeq = null;
            string strContactPersonSeq = null;
            DataTable dtb = (DataTable)Session["M_FIM_MoneyRequestTravelers"];
            DataRow dr = dtb.Rows[(int)ViewState["Index"]];

            dr["traveler_seq"] = main.ConvertToDB(strTravelSeq);
            dr["money_req_seq"] = main.ConvertToDB(strMoneyReqSeq);
            //dr["traveler_seq"] = (strTravelSeq.Length > 0 ? strTravelSeq : null);
            //dr["money_req_seq"] = (strMoneyReqSeq.Length > 0 ? strMoneyReqSeq : null);

            if (rblTravelerType.SelectedValue == "1")
            {
                strEmpSeq = DropDownList_Emp2.GetSelectedValue();

                dr["emp_seq"] = main.ConvertToDB(strEmpSeq);
                dr["job_site_seq"] = main.ConvertToDB(lblJobSiteSeq.Text);
                dr["pos_seq"] = main.ConvertToDB(lblPosSeq.Text);
                dr["class_seq"] = main.ConvertToDB(lblClassSeq.Text);
                dr["old_class_seq"] = main.ConvertToDB(lblOldClassSeq.Text);

                dr["traveler_name"] = main.ConvertToDB(DropDownList_Emp2.GetComboBox().Text);
                dr["job_site_name"] = main.ConvertToDB(lblJobSiteName.Text);
                dr["pos_name"] = main.ConvertToDB(lblPosName.Text);
                dr["class_name"] = main.ConvertToDB(lblClassName.Text);
                dr["old_class_name"] = main.ConvertToDB(lblOldClassName.Text);
            }
            else
            {
                strContactSeq = DropDownList_Contact2.GetSelectedValue();
                //strContactPersonSeq = DropDownList_ContactPerson2.GetSelectedValue();

                dr["contact_seq"] = main.ConvertToDB(strContactSeq);
                dr["contact_person_seq"] = main.ConvertToDB(strContactPersonSeq);

                if (DropDownList_Contact2.GetSelectedValue().Length > 0)
                {
                    dr["traveler_name"] = main.ConvertToDB(DropDownList_Contact2.GetComboBox().Text);
                }
                else
                {
                    dr["traveler_name"] = "";
                }
            }

            RepeaterTraveler.DataSource = dtb;
            RepeaterTraveler.DataBind();

            Session["M_FIM_MoneyRequestTravelers"] = dtb;
            ResetControl();
        }

        protected void cmdCancel1_Click(object sender, EventArgs e)
        {
            ResetControl();
        }

        protected void ResetControl()
        {
            lblTravelerSeq.Text = "";
            lblMoneyReqSeq.Text = "";
            DropDownList_Emp2.SetSelectedValue("");
            DropDownList_Emp2.SelectedIndexChanged("-1");
            DropDownList_Contact2.SetSelectedValue("");
            //DropDownList_ContactPerson2.SetSelectedValue("");

            UpdateUI2("AddNew");
        }

        protected void cmdAddNew_Click(object sender, EventArgs e)
        {
            AddNew();
        }
    }
}
